import 'package:casdon/modules/me/data/api/flower_list_api.dart';
import 'package:casdon/modules/me/domain/states/flower_list_state.dart';
import 'package:casdon/modules/me/domain/usecase/flower_list_usecase.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class FlowerListNotifier extends AutoDisposeAsyncNotifier<FlowerListState> {
  bool _isRefreshing = false;
  bool _isLoadingMore = false;

  @override
  Future<FlowerListState> build() async {
    return _fetchFirstPage();
  }

  Future<void> refresh() async {
    if (_isRefreshing) return;
    _isRefreshing = true;

    try {
      final newState = await _fetchFirstPage();
      state = AsyncValue.data(newState);
    } catch (e, st) {
      state = AsyncValue.error(e, st);
    } finally {
      _isRefreshing = false;
    }
  }

  Future<void> loadMore() async {
    if (_isLoadingMore) return;
    
    final current = state.valueOrNull;
    if (current == null || current.isLoadingMore || !current.hasMore) return;

    _isLoadingMore = true;
    state = AsyncValue.data(current.copyWith(isLoadingMore: true));

    try {
    final nextPage = current.page + 1;
    final pageSize = 20;
    final ret = await ref
        .read(flowerListUsecaseProvider)
        .execute(pageNum: nextPage, pageSize: pageSize);

      // 去重：基于 followUuid
      final existingIds = current.data.map((e) => e.followUuid).toSet();
      final newData = (ret?.rows ?? [])
          .where((item) => !existingIds.contains(item.followUuid))
          .toList();

    state = AsyncValue.data(
      FlowerListState(
          data: [...current.data, ...newData],
        page: nextPage,
        totalSize: ret?.total ?? 0,
        pageSize: current.pageSize,
        isLoadingMore: false,
        hasMore:
              (ret?.total ?? 0) > current.data.length + newData.length,
      ),
    );
    } catch (e, st) {
      state = AsyncValue.error(e, st);
    } finally {
      _isLoadingMore = false;
    }
  }

  Future<FlowerListState> _fetchFirstPage() async {
    final firstPage = 1;
    final pageSize = 20;
    final ret = await ref
        .read(flowerListUsecaseProvider)
        .execute(pageNum: firstPage, pageSize: pageSize);

    return FlowerListState(
      data: ret?.rows ?? [],
      page: firstPage,
      totalSize: ret?.total ?? 0,
      pageSize: pageSize,
      isLoadingMore: false,
      hasMore: (ret?.total ?? 0) > pageSize,
    );
  }

  /// 更新指定 flower 的关注状态
  void updateFlowerFollowStatus(String followUuid, bool isFollowed) {
    final current = state.valueOrNull;
    if (current == null) return;

    final updatedData = current.data.map((flower) {
      if (flower.followUuid == followUuid) {
        // 创建新的 Flower 实例，更新关注状态
        return Flower(
          followUuid: flower.followUuid,
          followUserNickname: flower.followUserNickname,
          followUserAvatars: flower.followUserAvatars,
          isFollow: isFollowed, // 更新关注状态
          followTime: flower.followTime,
        );
      }
      return flower;
    }).toList();

    state = AsyncValue.data(current.copyWith(data: updatedData));
  }
}

final flowerListNotifierProvider =
    AutoDisposeAsyncNotifierProvider<FlowerListNotifier, FlowerListState>(
      FlowerListNotifier.new,
    );
